package com.example.seckill.config;

import com.alibaba.fastjson.JSON;
import com.example.seckill.response.Response;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class ResultResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(final MethodParameter returnType, final Class<? extends HttpMessageConverter<?>> converterType) {
        return !returnType.getGenericParameterType().equals(Response.class);// 1
    }

    @Override
    public Object beforeBodyWrite(final Object body, final MethodParameter returnType, final MediaType selectedContentType,
                                  final Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  final ServerHttpRequest request, final ServerHttpResponse response) {
        if (body == null || body instanceof Response) {
            return body;
        }
        final Response<Object> result = new Response<>();
        result.setCode(200);
        result.setMsg("操作成功");
        result.setData(body);
        if (returnType.getGenericParameterType().equals(String.class)) {
            //ObjectMapper objectMapper = new ObjectMapper();
            result.setMsg(body.toString());
            result.setData(null);
            return JSON.toJSONString(result);
            //try {
            //    return JSON.toJSONString(result);
            //    //return objectMapper.writeValueAsString(result);
            //} catch (JsonProcessingException e) {
            //    throw new RuntimeException("将 Response 对象序列化为 json 字符串时发生异常", e);
            //}
        }
        return result;
    }
}

